<?php

namespace App\Models\FeishuCallingCard;

use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use Illuminate\Database\Eloquent\Relations\HasOne;

class FeishuCallingCardUsersStoriesLog extends BaseModel
{
    use KfSoftDeletes;

    protected $table = 'feishu_calling_card_users_stories_log';

    protected $fillable =
        [
            'storiesId',
            'usersId',
            'source',
            'openTime',
            'exitTime',
            'duration',
            'isReadCompleted',
            'isClickJoin',
            'type',
            'createdAt',
            'createdByUid',
            'updatedAt',
            'updatedByUid',
        ];

    // 是否完成阅读
    const NOT_READ_COMPLETE = 0;
    const READ_COMPLETE     = 1;// 是

    // 是否点击加盟
    const NOT_CLICK_JOIN = 0;
    const CLICK_JOIN     = 1;   // 是

    // 类型
    const TYPE_OPEN_ARTICLE = 1;// 进入文章
    const TYPE_HEARTBEAT    = 2;// 心跳更新数据
    const TYPE_EXIT_ARTICLE = 3;// 离开事件(更新数据)
    const TYPE_AUTO_OFF     = 4;// 进入文章

    const TYPE_TEXT_MAPPING = [
        self::TYPE_OPEN_ARTICLE => '进入文章',
        self::TYPE_HEARTBEAT    => '心跳更新数据',
        self::TYPE_EXIT_ARTICLE => '离开事件',
        self::TYPE_AUTO_OFF     => '脚本自动关闭',
    ];

    const SOURCE_WECHAT_APPLET   = 1;
    const SOURCE_WECHAT_OFFICIAL = 2;

    const SOURCE_TEXT_MAPPING = [
        self::SOURCE_WECHAT_APPLET   => '微信加盟小程序',
        self::SOURCE_WECHAT_OFFICIAL => '微信服务号',
    ];

    /**
     * @return HasOne
     */
    public function usersRel(): HasOne
    {
        return $this->hasOne(FeishuCallingCardUser::class, 'id', 'usersId');
    }

    /**
     * @return HasOne
     */
    public function storiesRel(): HasOne
    {
        return $this->hasOne(FeishuCallingCardStory::class, 'id', 'storiesId');
    }

    /**
     * @return HasOne
     */
    public function articleRel(): HasOne
    {
        return $this->hasOne(FeishuCallingCardsArticle::class, 'id', 'storiesId');
    }


    public static function createData($data)
    {
        return self::query()->create($data);
    }

    public static function updateData($id, $data): int
    {
        return self::query()->where('id', $id)->update($data);
    }

    // 查询当前用户查看文章未关闭记录
    public static function getInfo(int $storiesId, string $usersId)
    {
        return self::query()
            ->where('storiesId', $storiesId)
            ->where('usersId', $usersId)
            ->whereIn('type', [self::TYPE_OPEN_ARTICLE, self::TYPE_HEARTBEAT])
            ->orderByDesc('id')
            ->first();
    }
}
